package com.demo.controller;


import cn.hutool.core.date.DateUtil;
import com.demo.entity.Dictionary;
import com.demo.entity.from.DictionaryFrom;
import com.demo.response.Result;
import com.demo.service.IDictionaryService;
import com.demo.util.TimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据字典表非固定值的可后期增变的及全局信息如医院名称、医院logo等 前端控制器
 *
 * @author zm
 * @since 2020-11-24
 */
@Slf4j
@RestController
@RequestMapping("/dictionary")
@Api(tags = "字典类")
public class DictionaryController {
    @Autowired
    IDictionaryService iDictionaryService;

    @ApiOperation("新增数据字典信息")
    @PostMapping("/addDictionary")
    public Result addDictionary(@Validated @RequestBody Dictionary dictionary, BindingResult result) {
        if (result.hasErrors()) {
            return Result.error(result.getFieldError().getDefaultMessage());
        }
        return iDictionaryService.addDictionary(dictionary);
    }

    @ApiOperation("批量更新数据字典信息")
    @PostMapping("/updateDictionary")
    public Result updateDictionary(@RequestBody List<DictionaryFrom> list, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            return Result.error(result.getFieldError().getDefaultMessage());
        }
        return iDictionaryService.updateDictionary(list);
    }

    @ApiOperation("查询消息推送设置")
    @GetMapping("/getMesgPush")
    public Result getMesgPush(@RequestParam(name = "parentDictionaryCode") Integer parentDictionaryCode) {
        return iDictionaryService.getMesgPush(parentDictionaryCode);
    }

    @ApiOperation("删除数据字典信息")
    @GetMapping("/deleteDictionary")
    public Result deleteDictionary(@RequestParam(name = "dictionaryCode") Integer dictionaryCode,
                                   @RequestParam(name = "deletedUserId") Integer deletedUserId) {
        return iDictionaryService.deleteDictionary(dictionaryCode, deletedUserId);
    }

    @ApiOperation("数据字典详情")
    @GetMapping("/getDictionaryDesc")
    public Result getDictionaryDesc(@RequestParam(name = "dictionaryCode") Integer dictionaryCode) {
        return Result.success(iDictionaryService.getDictionaryDesc(dictionaryCode));
    }

    @ApiOperation(value = "查询医院名称")
    @GetMapping("/selectHospitalName")
    public Result selectHospitalName() {
        return Result.success(iDictionaryService.selectHospitalName());
    }

    @ApiOperation(value = "查询医院LOGO")
    @GetMapping("/selectHospitalLogo")
    public Result selectHospitalLogo() {
        return Result.success(iDictionaryService.selectHospitalLogo());
    }

    @ApiOperation(value = "图片上传")
    @PostMapping("/file")
    @ResponseBody
    public List<String> saveMultiFile(MultipartHttpServletRequest multipartHttpServletRequest) throws IOException {
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        List<String> fileNameList = new ArrayList<>();
        for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
            file = entry.getValue();
            if (!file.isEmpty()) {

                //生成一级目录
                String str2 = System.getProperty("user.dir") + "/upload";
                File fs = new File(str2);
                if (fs.exists()) {
                    if (fs.isDirectory()) {
                        log.info("该文件夹存在");
                    } else {
                        log.info("存在相同的名称文件，无法创建目录");
                    }
                } else {
                    fs.mkdir();
                    log.info("文件不存在，创建它...");
                }

                //生成二级目录
                String date = DateUtil.format(new Date(), "yyyy-MM-dd");
                String twoFile = str2 + "/" + date;
                File fileTwo = new File(twoFile);
                if (fileTwo.exists()) {
                    if (fileTwo.isDirectory()) {
                        log.info("该文件夹存在");
                    } else {
                        log.info("存在相同的名称文件，无法创建目录");
                    }
                } else {
                    fileTwo.mkdir();
                    log.info("文件不存在，创建它...");
                }

                String fileName = generateFileName(Objects.requireNonNull(file.getOriginalFilename()));
                String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase() + "-" + fileName;
                String p = fileTwo + "/" + uuid;
                fileNameList.add("/upload/" + date + "/" + uuid);
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(p));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    throw e;
                }
            }
        }
        return fileNameList;
    }


    /**
     * 读取源文件名，修改为不重复的文件名
     *
     * @param originalFilename
     * @return
     */
    private String generateFileName(String originalFilename) {
        List<String> sufList = Arrays.stream(originalFilename.split("\\.")).collect(Collectors.toList());
        String suf = sufList.get(sufList.size() - 1);
        String pre = TimeUtil.getSecondsTimeStampStr();
        return pre + "." + suf;
    }


}
